// 菜单请求工具类
import { getRequest } from "./api";

// 初始化菜单
export const initMenu = (router,store)=>{
    
    // 如果已经有菜单了
    if (store.state.routes.length > 0) {
        return;
    }
    getRequest('/system/cfg/menu').then(data=>{
        if (data){
            // 格式化好的Router
            let fmtRoutes = formatRoutes(data);
            // 添加到router
            router.addRoutes(fmtRoutes);
            // 将数据存入vuex
            store.commit('initRoutes',fmtRoutes)
			// 连接websocket
			store.dispatch('connect')

        }
    })
}

// 格式化路由
export const formatRoutes = (routes) =>{
    let fmtRoutes = [];
    routes.forEach(router=>{
        let{
            path,
            component,
            name,
            iconCls,
            children
        } = router;
        // 递归
        if (children && children instanceof Array) {
            children = formatRoutes(children)
        }
        let fmRouter = {
            path:path,
            name:name,
            iconCls:iconCls,
            children:children,
            component(resolve){
                if (component.startsWith("Home")) {
                    require(['../views/'+component+'.vue'],resolve)
                }
                if (component.startsWith("Emp")){
                    require(['../views/emp/'+component+'.vue'],resolve)
                }
                if (component.startsWith("Per")){
                    require(['../views/per/'+component+'.vue'],resolve)
                }
                if (component.startsWith("Sal")){
                    require(['../views/sal/'+component+'.vue'],resolve)
                }
                if (component.startsWith("Sta")){
                    require(['../views/sta/'+component+'.vue'],resolve)
                }
                if (component.startsWith("Sys")){
                    require(['../views/sys/'+component+'.vue'],resolve)
                }
            }
        }
        fmtRoutes.push(fmRouter)
    });
    return fmtRoutes;
}